package Classic150;

import Tree.TreeNode;

import java.util.*;

public class 二叉树的锯齿形层序遍历 {
    /*
        通过标记和双向队列改变存储时的顺序
     */
    public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
        List<List<Integer>> res = new ArrayList<>();
        if (root == null) return res;
        Queue<TreeNode> queue = new LinkedList<>();
        boolean flag = true;
        queue.offer(root);
        while (!queue.isEmpty()) {
            Deque<Integer> deque = new ArrayDeque<>();
            int size = queue.size();
            while(size-- > 0) {
                TreeNode node = queue.poll();
                if (flag) deque.addLast(node.val);
                else deque.addFirst(node.val);
                if (node.left != null) queue.offer(node.left);
                if (node.right != null) queue.offer(node.right);
            }
            res.add(new LinkedList<>(deque));
            flag = !flag;
        }
        return res;
    }
}
